#/usr/bin/python
import os
import hashlib
import time
import json
import stat
import mimetypes
import sys
import gzip

root = "/home/patrick/netbeans-7.2"
#root = "/home/patrick"
#root = "/run/media/patrick/3b07aa79-2b27-4c0f-b829-f4ad49a105cf/home/patrick/X-Files/03"
name = "Test"

class profile_process():
    def __init__(self):
        self.profile_name = ""
        self.c_revision = 0
        self.t_revision = 0
        self.comment = ""
        self.element = {}


    def name(self, name):
        self.profile_name = name

    def add(self, pid):
        properties = self.get_properties(pid)
        #revisions = {}
        exe = properties["executable"]
        if exe in self.element:
            self.element[properties["executable"]].append(properties)
        else:
            self.element[properties["executable"]] = []
            self.element[properties["executable"]].append(properties)

    def load(self, name):
        print "to do"

    def save(self):
        #f = gzip.open('test.gzip', 'w')
        #f.write(json.dumps(self.element, sort_keys=True, indent=4))
        #f.flush()
        #os.fsync(f.fileno())
        #f.close()
        print json.dumps(self.element, sort_keys=True, indent=4)
    
    def get_properties(self, pid):
        properties = {}
        status = open(os.path.join("/proc", pid, "status"), "r").read().split("\n")
        stats = open(os.path.join("/proc", pid, "stat"), "r").read().split(" ")
        name = stats[1]
        nice = stats[18]
        uid = {}
        uid["real"] = status[6].split("\t")[1]
        uid["effective"] = status[6].split("\t")[2]
        uid["savedset"] = status[6].split("\t")[3]
        uid["filesystem"] = status[6].split("\t")[4]
        gid = {}
        gid["real"] = status[7].split("\t")[1]
        gid["effective"] = status[7].split("\t")[2]
        gid["savedset"] = status[7].split("\t")[3]
        gid["filesystem"] = status[7].split("\t")[4]
        try:
            properties["executable"] = os.readlink(os.path.join("/proc", pid, "exe"))
        except:
            properties["executable"] = name
        properties["uid"] = uid
        properties["gid"] = gid
        properties["cmdline"] = open(os.path.join("/proc", pid, "cmdline"), "r").read()
        properties["limits"] = open(os.path.join("/proc", pid, "limits"), "r").read().split("\n")
        properties["environ"] = open(os.path.join("/proc", pid, "cmdline"), "r").read()
        properties["cwd"] = os.readlink(os.path.join("/proc", pid, "cwd"))
        properties["root"] = os.readlink(os.path.join("/proc", pid, "root"))
        properties["name"] = name
        properties["nice"] = nice
        return properties




prop = profile_process()
prop.name = "Test"
pids= [pid for pid in os.listdir('/proc') if pid.isdigit()]
print "Number of process : " + str(len(pids))
for pid in pids:
    prop.add(pid)

prop.save()


